package com.api;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FilterApi {

    private Configuration conf;
    private Connection conn;
    private Admin admin;

    @Before
    public void init() throws IOException {
        // 创建配置文件
        conf = HBaseConfiguration.create();
        // 加载zookeeper的配置
        conf.set("hbase.zookeeper.quorum", "node02,node03,node04");
        // 获取连接
        conn = ConnectionFactory.createConnection(conf);
        // 获取admin对象
        admin = conn.getAdmin();
    }

    /**
     * scan扫描多行数据
     */
    @Test
    public void scanTest() throws Exception {
        // 要先获取表
        TableName tableName = TableName.valueOf("api_test", "student");
        // 获取table对象
        Table table = conn.getTable(tableName);

        Scan scan = new Scan();

//        scan.setFilter()


        // 扫描一批数据
        ResultScanner scanner = table.getScanner(scan);

        printScanner(scanner);

        table.close();

    }



    @Test
    public void test1() throws Exception {
        // 要先获取表
        TableName tableName = TableName.valueOf("api_test", "student");
        // 获取table对象
        Table table = conn.getTable(tableName);

        Scan scan = new Scan();


        ResultScanner scanner = table.getScanner(scan);
        printScanner(scanner);
    }

    // 打印扫描结果
    private void printScanner(ResultScanner scanner) {
        int count = 0;
        for (Result result : scanner) {
            String id = new String(result.getRow());
            String name = Bytes.toString(result.getValue("info".getBytes(), "name".getBytes()));
            String age = Bytes.toString(result.getValue("info".getBytes(), "age".getBytes()));
            String gender = Bytes.toString(result.getValue("info".getBytes(), "gender".getBytes()));
            String clazz = Bytes.toString(result.getValue("info".getBytes(), "clazz".getBytes()));
            String ct = Bytes.toString(result.getValue("info".getBytes(), "ct".getBytes()));
            System.out.println("id:" + id + ",name:" + name + ",age:" + age + ",gender:" + gender
                    + ",clazz:" + clazz + ",ct:" + ct);
            count++;
        }
        System.out.println("本次scan了 " + count + " 行数据！！！");
    }


    @After
    public void afterTest() throws IOException {
        admin.close();
        conn.close();
    }
}
